import { ComponentClass } from "../components/ComponentClass";
import { e, style } from "../utils/html";
import { app } from "../utils/global";
import { TileEditor } from "../components/TileEditor";
import { PageClass } from "./PageClass";
import { getText } from "../utils/translate";
// style
const pageContent = {
  width: "100%",
  maxWidth: "720px",
  margin: "0 auto",
}
const tileEditorCanvas = {
  width: "80%",
  margin: "0 10%",
  border: "1px solid",
}

export class PageTileEditor extends PageClass{
  constructor(){
    super();
    this.__setupElement();
    this.__listenSelectTileIndexChange = this.__listenSelectTileIndexChange.bind(this);
    app.register(app.k.EVENT_SELECT_TILE_CHANGE, this.__listenSelectTileIndexChange);
  }
  __setupElement(){
    let data = app.get(app.k.SELECT_TILE_DATA, new Uint8Array([ 0, 0, 0, 0, 0, 0, 0, 0 ]));
    let w = app.get(app.k.SELECT_TILE_WIDTH, 8);
    let h = app.get(app.k.SELECT_TILE_HEIGHT, 8);
    this.tileEditor = new TileEditor(
      data,
      w, h, Math.floor(256/w), [0, 0, 0],
      (x, y, tileEditor, event)=>{
        if (app.get(app.k.SELECT_TILE_INDEX, -1) < 0){
          // alert("You should select a tile before edit it!")
          return; // no select tile
        }
        if (event.buttons === 1){
          tileEditor.setPixel(x, y, 1);
        }else if (event.buttons === 2){
          tileEditor.setPixel(x, y, 0);
        }else{
          return;
        }
        app.set(app.k.SELECT_TILE_DATA, tileEditor.buffer);
        app.set(app.k.EVENT_SELECT_TILE_DATA_CHANGE, true); // trigger tile selector update
      }
    );
    style(this.tileEditor.element, tileEditorCanvas);
    this.element = e("div",{style: pageContent},
      e("p", {style:{width:"100%",textAlign:"center"}}, getText("tile_editor_top_tips")),
      this.tileEditor.element,
    );
  }
  __listenSelectTileIndexChange(){
    this.__setupElement();
  }
}